//
//  ChartXAxisView.m
//  ChartDemoX
//
//  Created by yuanpt on 17/5/6.
//  Copyright © 2017年 yuanpt. All rights reserved.
//

#import "ChartXAxisView.h"
#import "ChartView.h"
#import "UIView+Extension.h"

@interface ChartXAxisView()

@property (nonatomic, strong) NSMutableArray *labelsFrameArray;

@end

@implementation ChartXAxisView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }

    return self;
}


- (NSMutableArray<UILabel *> *)labels {
    if (!_labels) {
        _labels = @[].mutableCopy;
    }
    return _labels;
}

- (void)updateLabels {
    [self.labels enumerateObjectsUsingBlock:^(UILabel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.superview) {
            [obj removeFromSuperview];
        }
    }];
    [self.labels removeAllObjects];
    [self.labelsFrameArray removeAllObjects];
    
    NSInteger count = (NSInteger)self.chartView.xMaxValue;
    for (NSInteger i = 0; i <= count; ++i) {
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:11.0f];
        label.textAlignment = NSTextAlignmentCenter;
        CGFloat labelWidth = self.chartView.scrollView.sy_width / self.chartView.xPerScreen;
        label.text = @(0 + i * self.chartView.xGridValue).stringValue;
        [self.labels addObject:label];
        label.sy_width = labelWidth;
        label.sy_height = 21;
        label.sy_y = 0;
        label.sy_x = -labelWidth *0.5 + i * labelWidth;
        [self addSubview:label];
        [self.labelsFrameArray addObject:[NSValue valueWithCGRect:label.frame]];
    }
}

- (void)updateLabelPositonWithOffsetX:(CGFloat)x {
    [self.labelsFrameArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGRect rect = [obj CGRectValue];
        rect.origin.x -= x;
        UILabel *label = self.labels[idx];
        label.frame = rect;
        CGFloat labelWidth = label.sy_width;
        CGFloat centerX = label.sy_centerX;
        if (0 <= centerX && centerX <= self.sy_width) {
            label.alpha = 1.0f;
        } else {
            CGFloat delta = centerX < 0 ? centerX : centerX - self.sy_width;
            delta = fabs(delta);
            CGFloat result = (1 - (delta / labelWidth * 1.7));
            label.alpha = result > 0 ? result : 0;
        }
    }];
}

- (void)layoutSubviews {
    [super layoutSubviews];
}

- (NSMutableArray *)labelsFrameArray {
    if (!_labelsFrameArray) {
        _labelsFrameArray = @[].mutableCopy;
    }
    return _labelsFrameArray;
}

@end
